package com.github.postsanf.yinian.activity;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Point;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.UiSettings;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.bean.YNStatus;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.SelectedImg;
import com.github.postsanf.yinian.constants.YNSingleton;
import com.github.postsanf.yinian.entity.YNStatusResponse;
import com.github.postsanf.yinian.entity.YNUpTokenResponse;
import com.github.postsanf.yinian.service.UpLoadService;
import com.github.postsanf.yinian.utils.Bimp;
import com.github.postsanf.yinian.utils.DisplayUtils;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.SizeFormat;
import com.github.postsanf.yinian.utils.StringUtils;
import com.github.postsanf.yinian.utils.SystemUtils;
import com.github.postsanf.yinian.utils.TimeUtils;
import com.github.postsanf.yinian.widget.MapContainer2;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.UUID;

public class LocationEditActivity extends BaseActivity implements View.OnClickListener, LocationSource, AMapLocationListener {
    private ImageView iv_back;
    private TextView imagelocal_send;
    private RelativeLayout rl_map_container;
    private TextView imagelocal_ed_sure;
    private RelativeLayout imagelocal_edit_cover;
    private ImageButton imagelocal_edit_cover2;
    private TextView imagelocaledit_location_show;
    private TextView imagelocaledit_mic_tx;
    private ImageView iv_imagelocaledit_mic;
    private ImageView iv_imagelocaledit_mic_close;
    private EditText et_imagelocaledit;
    private ImageView iv_imagelocaledit_album;
    private TextView tv_imagelocaledit_albumnum;
    private ImageView imagelocaledit_albumclose;
    private ScrollView locationedit_sv;
    private MapView mMapView;
    private TextView locationedit_mapview_tt;
    private AMap aMap;
    LocationSource.OnLocationChangedListener mListener;
    AMapLocationClient mlocationClient;
    AMapLocationClientOption mlocationOption;
    String locationtx = "";
    private RelativeLayout imagelocaledit_aite;
    private RelativeLayout imagelocaledit_aite_show;
    private LinearLayout aite_sel_hor;
    private UiSettings mUiSettings;//定义一个UiSettings对象
    private UploadManager mUpManager;
    private MapContainer2 map_container;
    private ConnectivityManager mConnectivityManager;
    private String fsize;
    SharedPreferences.Editor editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerBoradcastReceiver();
        setContentView(R.layout.yn_locationedit);
        locationtx = getIntent().getStringExtra("locationtx");
        mUpManager = application.getUploadManager();
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        editor = getSharedPreferences(ACTIONs.mynetwork, 0).edit();
        mTempDir = new File(Environment.getExternalStorageDirectory(), "yinian/temp");
        if (!(mTempDir.mkdir() || mTempDir.isDirectory())) {
            mTempDir.mkdirs();
        }
        initView(savedInstanceState);
    }

    private void initView(Bundle savedInstanceState) {
        iv_back = (ImageView) findViewById(R.id.iv_back);
        iv_back.setOnClickListener(this);
        findViewById(R.id.word_kit).setOnClickListener(this);
        findViewById(R.id.rl_pop_top).setOnClickListener(this);
        locationedit_sv = (ScrollView) findViewById(R.id.locationedit_sv);
        findViewById(R.id.imagelocaledit_album).setOnClickListener(this);
        mMapView = (MapView) findViewById(R.id.locationedit_mapview);
        locationedit_mapview_tt = (TextView) findViewById(R.id.locationedit_mapview_tt);
        map_container = (MapContainer2) findViewById(R.id.map_container);
        map_container.setScrollView(locationedit_sv);
        mMapView.onCreate(savedInstanceState);
        if (aMap == null) {
            aMap = mMapView.getMap();
        }
        mUiSettings = aMap.getUiSettings();
        aMap.setLocationSource(this);
        aMap.setMyLocationEnabled(true);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(17));
        aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {
            }

            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {
                Point point = new Point(400, 400);
                LatLng latLng = aMap.getProjection().fromScreenLocation(point);
//                double latitude = latLng.latitude;
//                double longitude = latLng.longitude;
//                Geocoder gc = new Geocoder(LocationEditActivity.this, Locale.getDefault());
//                List<Address> locationList = null;
//                try {
//                    locationList = gc.getFromLocation(latitude, longitude, 1);
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//                Address address = locationList.get(0);
//                Log.i("xjs", "address=====>" + address.toString());
            }
        });
        iv_imagelocaledit_album = (ImageView) findViewById(R.id.iv_imagelocaledit_album);
        tv_imagelocaledit_albumnum = (TextView) findViewById(R.id.tv_imagelocaledit_albumnum);
        imagelocaledit_albumclose = (ImageView) findViewById(R.id.imagelocaledit_albumclose);
        imagelocaledit_albumclose.setOnClickListener(this);
        imagelocal_send = (TextView) findViewById(R.id.imagelocal_send);
        imagelocal_ed_sure = (TextView) findViewById(R.id.imagelocal_ed_sure);
        imagelocal_send.setOnClickListener(this);
        imagelocal_ed_sure.setOnClickListener(this);
        et_imagelocaledit = (EditText) findViewById(R.id.et_imagelocaledit);
        et_imagelocaledit.clearFocus();
        et_imagelocaledit.setCursorVisible(false);
        rl_map_container = (RelativeLayout) findViewById(R.id.rl_map_container);
        imagelocal_edit_cover = (RelativeLayout) findViewById(R.id.imagelocal_edit_cover);
        imagelocal_edit_cover2 = (ImageButton) findViewById(R.id.imagelocal_edit_cover2);
        imagelocal_edit_cover2.setOnClickListener(this);
        findViewById(R.id.imagelocaledit_mic).setOnClickListener(this);
        iv_imagelocaledit_mic = (ImageView) findViewById(R.id.iv_imagelocaledit_mic);
        iv_imagelocaledit_mic_close = (ImageView) findViewById(R.id.iv_imagelocaledit_mic_close);
        iv_imagelocaledit_mic_close.setOnClickListener(this);
        imagelocaledit_mic_tx = (TextView) findViewById(R.id.imagelocaledit_mic_tx);
        imagelocaledit_aite = (RelativeLayout) findViewById(R.id.imagelocaledit_aite);
        imagelocaledit_aite_show = (RelativeLayout) findViewById(R.id.imagelocaledit_aite_show);
        aite_sel_hor = (LinearLayout) findViewById(R.id.aite_sel_hor);
        imagelocaledit_aite.setOnClickListener(this);
        aite_sel_hor.setOnClickListener(this);
        imagelocaledit_aite_show.setOnClickListener(this);

        imagelocaledit_location_show = (TextView) findViewById(R.id.imagelocaledit_location_show);
        imagelocaledit_location_show.setText(locationtx);
        locationedit_mapview_tt.setText(locationtx);
        MainActivity.locationTx = locationtx;

        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setCancelable(false);
        mProgressDialog.setMessage(CommonConstants.TIP_LOAD_UP);
        sendBroadcast(new Intent("updateeditphone"));
        sendBroadcast(new Intent(ACTIONs.actionMIcText));
    }


    @Override
    public void activate(LocationSource.OnLocationChangedListener listener) {
        mListener = listener;
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(this);
            mlocationOption = new AMapLocationClientOption();
            //设置定位回调监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mlocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationOption.setOnceLocation(true);
            mlocationClient.setLocationOption(mlocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();//启动定位
        }
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (mListener != null && amapLocation != null) {
            if (amapLocation != null
                    && amapLocation.getErrorCode() == 0) {
                mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
            } else {
                String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
                Log.e("AmapErr", errText);
            }
        }
    }


    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                et_imagelocaledit.setCursorVisible(true);
                imagelocal_edit_cover.setVisibility(View.GONE);
                imagelocal_edit_cover2.setVisibility(View.VISIBLE);
                iv_back.setVisibility(View.GONE);
                imagelocal_send.setVisibility(View.GONE);
                imagelocal_ed_sure.setVisibility(View.VISIBLE);
                return false;
            } else {
                et_imagelocaledit.setCursorVisible(false);
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.word_kit:
                startActivity(new Intent(LocationEditActivity.this, TextEditKitActivity.class));
                break;
            case R.id.imagelocal_send:
                mProgressDialog.show();
                mUiSettings.setZoomControlsEnabled(false);
                MyLocationStyle myLocationStyle = new MyLocationStyle();
                myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(-1));
                myLocationStyle.strokeColor(R.color.transparent);
                myLocationStyle.radiusFillColor(R.color.transparent);
                mListener.onLocationChanged(null);
                aMap.clear();
                aMap.getMapScreenShot(new AMap.OnMapScreenShotListener() {
                    @Override
                    public void onMapScreenShot(Bitmap bitmap) {
                        if (null == bitmap) {
                            return;
                        }
                        saveBitmap(rl_map_container);
                        if (f.exists()) {
                            getTokenJieTu();
                        }
                    }
                });
                break;
            case R.id.rl_pop_top:
//            case R.id.imagelocal_edit_cover:
            case R.id.imagelocal_edit_cover2:
            case R.id.imagelocal_ed_sure:
                imagelocal_edit_cover.setVisibility(View.VISIBLE);
                imagelocal_edit_cover2.setVisibility(View.GONE);
                iv_back.setVisibility(View.VISIBLE);
                imagelocal_send.setVisibility(View.VISIBLE);
                imagelocal_ed_sure.setVisibility(View.GONE);
                InputMethodManager imm = (InputMethodManager)
                        getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                break;
            case R.id.imagelocaledit_album:
                startActivity(new Intent(LocationEditActivity.this, ImageLocalSelectActivity.class));
                break;
            case R.id.imagelocaledit_mic:
                Intent micIntent = new Intent(LocationEditActivity.this, MicAddActivity.class);
                startActivity(micIntent);
                break;
            case R.id.iv_imagelocaledit_mic_close:
                DelMicDialog();
                break;
            case R.id.imagelocaledit_aite:
                startActivity(new Intent(LocationEditActivity.this, AiteSelectActivity.class));
                break;
            case R.id.imagelocaledit_albumclose:
                DelImgDialog();
                break;
            case R.id.aite_sel_hor:
            case R.id.imagelocaledit_aite_show:
                startActivity(new Intent(LocationEditActivity.this, AiteSelectActivity.class));
                break;
            default:
                break;
        }
    }

    public void DelMicDialog() {
        android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this);
        builder.setCancelable(false);
        final android.support.v7.app.AlertDialog dlg = builder.create();
        dlg.show();
        Window window = dlg.getWindow();
        window.setContentView(R.layout.pub_dialog);
        window.setBackgroundDrawableResource(R.color.transparent);
        WindowManager.LayoutParams layout = dlg.getWindow().getAttributes();
        layout.width = DisplayUtils.getScreenWidthPixels(this) - DisplayUtils.dp2px(this, 35 * 2);
        dlg.getWindow().setAttributes(layout);
        TextView tt = (TextView) window.findViewById(R.id.pp_title);
        tt.setText("提示");
        TextView content = (TextView) window.findViewById(R.id.pp_content);
        content.setText("是否删除已录入的声音");
        TextView cancel = (TextView) window
                .findViewById(R.id.btn_cancel);
        cancel.setText("取消");
        cancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                dlg.cancel();
            }
        });
        final TextView ok = (TextView) window.findViewById(R.id.btn_ok);
        ok.setText("删除");
        ok.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                MainActivity.micpath = "";
                MainActivity.mp3IsExist = false;
                MainActivity.micUrl = "";
                MainActivity.timer = 0;
                MicAddActivity.mMp3FileName = "";
                sendBroadcast(new Intent(ACTIONs.actionMIcText));
                dlg.cancel();
            }
        });
    }

    public void DelImgDialog() {
        android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this);
        builder.setCancelable(false);
        final android.support.v7.app.AlertDialog dlg = builder.create();
        dlg.show();
        Window window = dlg.getWindow();
        window.setContentView(R.layout.pub_dialog);
        window.setBackgroundDrawableResource(R.color.transparent);
        WindowManager.LayoutParams layout = dlg.getWindow().getAttributes();
        layout.width = DisplayUtils.getScreenWidthPixels(this) - DisplayUtils.dp2px(this, 35 * 2);
        dlg.getWindow().setAttributes(layout);
        TextView tt = (TextView) window.findViewById(R.id.pp_title);
        tt.setText("提示");
        TextView content = (TextView) window.findViewById(R.id.pp_content);
        content.setText("是否删除已添加的所有照片？");
        TextView cancel = (TextView) window
                .findViewById(R.id.btn_cancel);
        cancel.setText("取消");
        cancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                dlg.cancel();
            }
        });
        final TextView ok = (TextView) window.findViewById(R.id.btn_ok);
        ok.setText("删除");
        ok.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                SelectedImg.mSelectedImage.clear();
                sendBroadcast(new Intent("updateImageNum"));
                dlg.cancel();
            }
        });
    }


    public String getphoneNames() {
        if (AiteSelectActivity.phoneNames.size() > 0) {
            String phones = null;
            for (int j = 0; j < AiteSelectActivity.phoneNames.size(); j++) {
                String strings = AiteSelectActivity.phoneNames.get(j);
                if (phones == null) {
                    phones = strings;
                } else {
                    phones = phones + "," + strings;
                }
            }
            return phones;
        } else {
            return "";
        }
    }


    private long getupstorge() {
        long totalSize = 0;
        for (int i = 0; i < SelectedImg.mSelectedImage.size(); i++) {
            String address = SelectedImg.mSelectedImage.get(i);
            if (!address.startsWith("http")) {
                File uploadImg = new File(address);
                long imgSize = uploadImg.length();
                totalSize += imgSize;
            }
        }
        return totalSize;
    }

    private void doUpImg(boolean isPause, String upplacepic) {
        mProgressDialog = ProgressDialog.show(this, "", CommonConstants.TIP_LOAD_UP);
        Intent mIntent = new Intent(this, UpLoadService.class);
        mIntent.setAction(ACTIONs.actionPublishElement);
        mIntent.putExtra(ACTIONs.aUid, application.getCurID() + "");
        mIntent.putExtra(ACTIONs.aGid, application.getCurGid() + "");
        mIntent.putExtra(ACTIONs.aContent, et_imagelocaledit.getText().toString());
        mIntent.putExtra(ACTIONs.upaudio, MainActivity.micUrl);
        mIntent.putExtra(ACTIONs.upplace, MainActivity.locationTx);
        mIntent.putExtra(ACTIONs.upplacepic, upplacepic);
        mIntent.putExtra(ACTIONs.upplaceLongitude, "");
        mIntent.putExtra(ACTIONs.upplaceLatitude, "");
        mIntent.putExtra(ACTIONs.uppeopleName, getphoneNames());
        mIntent.putExtra(ACTIONs.aisPause, isPause);
        mIntent.putExtra(ACTIONs.upmain, "3");
        mIntent.putExtra(ACTIONs.upstorage, SizeFormat.formatDouble(getupstorge(), SizeFormat.FZ_KB));
        mIntent.putExtra(ACTIONs.upsource, SystemUtils.getAppStoreName(LocationEditActivity.this, "UMENG_CHANNEL"));
        startService(mIntent);
        startActivity(new Intent(this, UpLoadActivity.class).putExtra(ACTIONs.IstoSetWifi, isPause));
        Intent upIntent = new Intent(ACTIONs.actionCloseAlbum);
        upIntent.putExtra(ACTIONs.aIsClearSelect, 1);
        sendBroadcast(upIntent);
        mProgressDialog.dismiss();
        finish();
    }


    private void UploadToYiNian(String upplacepic) {
        String urlsto = "https://api.zhuiyinanian.com/YinianProject/event/UploadEvent";
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, application.getCurID() + "");
        mParam.put(CommonConstants.YNS_GROUP_ID, application.getCurGid() + "");
        mParam.put(CommonConstants.YNS_CONTENT, et_imagelocaledit.getText().toString());
        mParam.put(CommonConstants.YNS_PIC_ADDRESS, "");
        mParam.put(CommonConstants.YNS_EPLACE, MainActivity.locationTx);
        mParam.put(CommonConstants.YNS_PIC_MODE, "private");
        mParam.put(CommonConstants.YNS_AUDIO, MainActivity.micUrl);
        mParam.put(CommonConstants.YNS_PLACE, MainActivity.locationTx);
        mParam.put(CommonConstants.YNS_PLACEPIC, upplacepic);
        mParam.put(CommonConstants.YNS_PLACELONGITUDE, "");
        mParam.put(CommonConstants.YNS_PLACELATITUDE, "");
        mParam.put(CommonConstants.YNS_PEOPLENAME, getphoneNames());
        mParam.put(CommonConstants.YNS_MAIN, "3");
        mParam.put(CommonConstants.YNS_SOURCE, SystemUtils.getAppStoreName(LocationEditActivity.this, "UMENG_CHANNEL"));
        String upstorage = SizeFormat.formatDouble(getupstorge(), SizeFormat.FZ_KB);
        mParam.put(CommonConstants.YNS_STORAGE, upstorage);
        StringRequest req = new StringRequest(urlsto)
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNStatusResponse resStatus = gson.fromJson(s, YNStatusResponse.class);
                        if (ReqUtils.isSuccess(resStatus.getCode())) {
                            Log.i("xjs", "uploadsssssss==>" + s.toString());
                            if (resStatus.getData() != null) {
                                YNStatus mstatus = resStatus.getData().get(0);
                                YNSingleton.getInstance().setCurStatus(mstatus);
                                // 通知动态更新
                                Intent mIntent = new Intent(ACTIONs.actionStatus);
                                mIntent.putExtra(ACTIONs.IsAdd, true);
                                mIntent.putExtra(ACTIONs.StatusId, mstatus.getEid());
                                sendBroadcast(mIntent);
                                sendBroadcast(new Intent(ACTIONs.actionAlbumInit));
                                sendBroadcast(new Intent(ACTIONs.actionGridWallUpdate));
                            }
                            File mTempDir = new File(Environment.getExternalStorageDirectory(), "yinian/temp");
                            if (mTempDir.exists()) {
                                mTempDir.delete();
                            }
                            Intent upIntent = new Intent(ACTIONs.actionCloseAlbum);
                            upIntent.putExtra(ACTIONs.aIsClearSelect, 1);
                            sendBroadcast(upIntent);
                            finish();
                        } else {
                            showToast(resStatus.getMsg());
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
//                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    String jieTuUrl;
    File f;
    String jieTuUrlkey;
    private ProgressDialog mProgressDialog;

    public void saveBitmap(View v) {
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "yinian/YiNian");
        if (!file.exists()) {
            file.mkdirs();
        }
        f = new File(file.getPath() + "/", System.currentTimeMillis() + ".png");
        jieTuUrl = f.getAbsolutePath();
        if (f.exists()) {
            f.delete();
        }
        Bitmap bm = Bitmap.createBitmap(v.getWidth(), v.getHeight(),
                Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bm);
        v.draw(canvas);
        try {
            FileOutputStream out = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private void getTokenJieTu() {
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynGetPrivateSpaceUploadToken))
                .setMethod(HttpMethods.Post)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNUpTokenResponse resToken = gson.fromJson(s, YNUpTokenResponse.class);
                        if (ReqUtils.isSuccess(resToken.getCode())) {
                            mUpManager.put(jieTuUrl, UUID.randomUUID().toString() + ".png", resToken.getData().get(0).getToken(),
                                    new UpCompletionHandler() {
                                        @Override
                                        public void complete(String key, ResponseInfo info, JSONObject res) {
                                        }
                                    }, new UploadOptions(null, null, false, new UpProgressHandler() {
                                        public void progress(String key, double percent) {
                                            if (percent == 1.0) {
                                                jieTuUrlkey = key;
                                                if (SelectedImg.mSelectedImage.size() > 0) {
//                                                    doUpImg(false, jieTuUrlkey);
                                                    fsize = SizeFormat.formatSize(getupstorge());
                                                    if (!ImageLocalSelectActivity.IsSmall) {
                                                        pd = ProgressDialog.show(LocationEditActivity.this, "", "发布中...", false, false);
                                                        mHandler.sendEmptyMessage(1);
                                                    } else {
                                                        pd = ProgressDialog.show(LocationEditActivity.this, "", "压缩中...", false, false);
                                                        new Thread() {
                                                            @Override
                                                            public void run() {
                                                                super.run();
                                                                for (int i = 0; i < SelectedImg.mSelectedImage.size(); i++) {
                                                                    if (!SelectedImg.mSelectedImage.get(i).startsWith("http")) {
                                                                        String mubiaostr = Bimp.compressImage2(SelectedImg.mSelectedImage.get(i), mTempDir);
                                                                        SelectedImg.mSelectedImage.set(i, mubiaostr);
                                                                    }
                                                                }
                                                                mHandler.sendEmptyMessage(1);
                                                            }
                                                        }.start();
                                                    }

                                                } else {
                                                    UploadToYiNian(jieTuUrlkey);
                                                }
                                            }
                                        }
                                    }, null));
                        } else {
                            showToast(resToken.getMsg());
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        mProgressDialog.dismiss();
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }


    private ProgressDialog pd;
    private File mTempDir;

    Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 1) {
                if (pd != null)
                    pd.dismiss();
                if (mConnectivityManager.getActiveNetworkInfo() != null && mConnectivityManager.getActiveNetworkInfo().isAvailable()) {
                    if (mConnectivityManager.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI) {
                        //WiFi网络
                        doUpImg(false, jieTuUrlkey);
                    } else if (mConnectivityManager.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_MOBILE) {
                        //3g网络
                        int netfrist = getSharedPreferences(ACTIONs.mynetwork, 0).getInt(ACTIONs.networkFrist, 0);
                        String nettype = getSharedPreferences(ACTIONs.mynetwork, 0).getString(ACTIONs.networkType, "");
                        if (!nettype.equals("") && nettype.equals(ACTIONs.network3GWIFI)) {
                            doUpImg(false, jieTuUrlkey);
                        } else {
                            if (netfrist == 0) {
                                FristNetWork(fsize);
                                editor.putInt(ACTIONs.networkFrist, 1);
                                editor.commit();
                            } else {
                                SecondNetWork(fsize);
                            }
                        }
                    }
                } else {
                    if (pd != null)
                        pd.dismiss();
                }
            }
        }
    };


    public void FristNetWork(String fsize) {
        final android.support.v7.app.AlertDialog dlg = new android.support.v7.app.AlertDialog.Builder(this).create();
        dlg.show();
        Window window = dlg.getWindow();
        window.setContentView(R.layout.publish_network_dialog);
        TextView tt = (TextView) window.findViewById(R.id.pp_title);
        tt.setText("您现在处于移动网络环境下，将消耗" + fsize + "流量，是否使用流量继续上传?");
        final TextView ok = (TextView) window.findViewById(R.id.btn_ep_ok);
        ok.setText("不允许");
        ok.setBackgroundColor(getResources().getColor(R.color.white));
        ok.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                doUpImg(true, jieTuUrlkey);
                dlg.cancel();
            }
        });
        final TextView cancel = (TextView) window
                .findViewById(R.id.btn_ep_cancel);
        cancel.setText("确定");
        cancel.setBackgroundColor(getResources().getColor(R.color.white));
        cancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                editor.putString(ACTIONs.networkType, ACTIONs.network3GWIFI);
                editor.commit();
                doUpImg(false, jieTuUrlkey);
                dlg.cancel();
            }
        });
    }

    public void SecondNetWork(String fsize) {
        final android.support.v7.app.AlertDialog dlg = new android.support.v7.app.AlertDialog.Builder(this).create();
        dlg.show();
        Window window = dlg.getWindow();
        window.setContentView(R.layout.publish_network_dialog);
        TextView tt = (TextView) window.findViewById(R.id.pp_title);
        tt.setText(">_< 您关闭了使用流量上传开关，你在使用3g/4g网络环境下，这会消耗您" + fsize + "流量，确定继续上传吗？");
        final TextView ok = (TextView) window.findViewById(R.id.btn_ep_ok);
        ok.setText("取消");
        ok.setBackgroundColor(getResources().getColor(R.color.white));
        ok.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                dlg.cancel();
            }
        });
        final TextView cancel = (TextView) window
                .findViewById(R.id.btn_ep_cancel);
        cancel.setText("仅一次");
        cancel.setBackgroundColor(getResources().getColor(R.color.white));
        cancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                doUpImg(false, jieTuUrlkey);
                dlg.cancel();
            }
        });
    }


    public void saveBitmapres(Bitmap bm) {
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "yinian/YiNian");
        if (!file.exists()) {
            file.mkdirs();
        }
        File f = new File(file.getPath() + "/", System.currentTimeMillis() + ".png");
//        jieTuUrl = f.getAbsolutePath();
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case "kitContent":
                    String ettext = et_imagelocaledit.getText().toString();
                    String text = intent.getStringExtra("text");
                    if (StringUtils.isEmpty(ettext)) {
                        et_imagelocaledit.setText(text);
                    } else {
                        et_imagelocaledit.setText(ettext + "\n" + text);
                    }
                    break;
                case ACTIONs.actionMIcText:
                    if (!StringUtils.isEmpty(MainActivity.micUrl)) {
                        if (MainActivity.mp3IsExist) {
                            iv_imagelocaledit_mic.setImageResource(R.drawable.icon_edit_mic);
                            iv_imagelocaledit_mic_close.setVisibility(View.VISIBLE);
                            imagelocaledit_mic_tx.setText(TimeUtils.secToTime(MainActivity.timer));
                        } else {
                            imagelocaledit_mic_tx.setText("添加声音");
                            iv_imagelocaledit_mic_close.setVisibility(View.GONE);
                            iv_imagelocaledit_mic.setImageResource(R.drawable.icon_edit_mic_before);
                        }
                    } else {
                        imagelocaledit_mic_tx.setText("添加声音");
                        iv_imagelocaledit_mic_close.setVisibility(View.GONE);
                        iv_imagelocaledit_mic.setImageResource(R.drawable.icon_edit_mic_before);
                    }
                    break;
                case "updateeditphone":
                    if (AiteSelectActivity.phoneNames.size() > 0) {
                        imagelocaledit_aite.setVisibility(View.GONE);
                        aite_sel_hor.removeAllViews();
                        textViews.clear();
                        for (int i = 0; i < AiteSelectActivity.phoneNames.size(); i++) {
                            aite_sel_hor.addView(CreateAiteTextView(AiteSelectActivity.phoneNames.get(i)));
                        }
                        imagelocaledit_aite_show.setVisibility(View.VISIBLE);
                    } else {
                        imagelocaledit_aite.setVisibility(View.VISIBLE);
                        imagelocaledit_aite_show.setVisibility(View.GONE);
                    }
                    break;
                case "updateImageNum":
                    if (SelectedImg.mSelectedImage.size() > 0) {
                        tv_imagelocaledit_albumnum.setText("已添加" + SelectedImg.mSelectedImage.size() + "张照片");
                        iv_imagelocaledit_album.setImageResource(R.drawable.icon_edit_album);
                        imagelocaledit_albumclose.setVisibility(View.VISIBLE);
                    } else {
                        tv_imagelocaledit_albumnum.setText("添加照片");
                        iv_imagelocaledit_album.setImageResource(R.drawable.icon_edit_album_before);
                        imagelocaledit_albumclose.setVisibility(View.GONE);
                    }
                    break;
            }
        }
    };

    private List<TextView> textViews = new ArrayList<>();

    private View CreateAiteTextView(String locationtx) {
        View lView = LayoutInflater.from(this).inflate(R.layout.yn_imagelocal_edit_locationlayout, null);
        TextView ltv = (TextView) lView.findViewById(R.id.location_layout);
        ltv.setText(locationtx);
        ltv.setTag(0);
        textViews.add(ltv);
        lView.setOnClickListener(AitetxListener);
        return lView;
    }

    View.OnClickListener AitetxListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            TextView ltv = (TextView) v.findViewById(R.id.location_layout);
            int tag = (int) ltv.getTag();
            if (tag != 1) {
                for (int i = 0; i < textViews.size(); i++) {
                    TextView othertx = textViews.get(i);
                    othertx.setTag(0);
                    ltv.setTextColor(Color.parseColor("#ffffff"));
                    othertx.setBackgroundResource(R.drawable.location_radio_btn);
                }
                ltv.setTextColor(Color.parseColor("#000000"));
                ltv.setBackgroundResource(R.drawable.location_radio_btn_yellow);
                ltv.setTag(1);
            } else {
                for (int i = 0; i < AiteSelectActivity.phoneNames.size(); i++) {
                    if (ltv.getText().toString().equals(AiteSelectActivity.phoneNames.get(i))) {
                        AiteSelectActivity.phoneNames.remove(i);
                    }
                }
                for (int i = 0; i < textViews.size(); i++) {
                    if (ltv.getText().toString().equals(textViews.get(i).getText().toString())) {
                        textViews.remove(i);
                        aite_sel_hor.removeViewAt(i);
                    }
                }
                if (AiteSelectActivity.phoneNames.size() == 0) {
                    imagelocaledit_aite.setVisibility(View.VISIBLE);
                    imagelocaledit_aite_show.setVisibility(View.GONE);
                }
            }
        }
    };

    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.actionMIcText);
        myIntentFilter.addAction("updateeditphone");
        myIntentFilter.addAction("updateImageNum");
        myIntentFilter.addAction("kitContent");
        registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    public void onResume() {
        super.onResume();
        mMapView.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        mMapView.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
        if (null != mlocationClient) {
            mlocationClient.onDestroy();
        }
        this.unregisterReceiver(mBroadcastReceiver);
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }
}
